# 定义 数据库工具类
import pymysql

class DBTools(object):
    # 创建连接
    @classmethod
    def __create_conn(cls):
        conn = pymysql.Connect(host="172.28.210.27", port=3306, user="root", password="10086", database="student",
                               charset="utf8")
        return conn
    # 查一条记录
    @classmethod
    def query_one(cls,sql):
        pass
        # 创建连接
        myconn = DBTools.__create_conn()
        # 创建游标
        my_cursor = myconn.cursor()
        #执行sql语句做查询
        my_cursor.execute(sql)
        #提取一条记录
        res = my_cursor.fetchone()
        # 关闭游标
        my_cursor.close()
        # 关闭连接
        my_cursor.close()
        return res

    # 增删改记录
    @classmethod
    def db_uid(cls,sql):
        my_conn = None
        my_cursor = None
        try:
            # 创建连接
            my_conn = DBTools.__create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行sql语句
            my_cursor.execute(sql)
            print("Affected rows", my_conn.affected_rows())
            # 提交事务
            my_conn.commit()
        except  Exception as err:
            print("执行增删改失败:",str(err))
            my_conn.rollback()
        finally:

             # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()
if __name__ == '__main__':
    result=DBTools.query_one("select*from course;")
    print("查询的结果为",result)
    DBTools.db_uid("update course set studentId = '2022212900' WHERE courseId = 1;")
